package org.slg.oracleproject.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slg.oracleproject.entity.User;
import org.slg.oracleproject.entity.dto.UserDTO;
import org.slg.oracleproject.respones.CommonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.slg.oracleproject.service.UserService;


/**
 * 控制层。
 *
 * @author 沙龙果
 * @since 2025年09月23日
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户信息模块")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 查询用户列表（普通用户和超管都可访问）
     */
    @GetMapping("/list")
    @Operation(summary = "查询用户列表", description = "需要user:list权限")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'USER') and hasPermission('', 'user:list')")
    public CommonResult listUsers() {
        return CommonResult.success(userService.list());
    }

    /**
     * 删除用户（仅超管可访问）
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户（仅超管可访问）", description = "需要超管权限和user:delete权限")
    @PreAuthorize("hasRole('SUPER_ADMIN') and hasPermission('', 'user:delete')")
    public CommonResult deleteUser(@PathVariable Integer id) {
        return CommonResult.success(userService.removeById(id));
    }


    @PostMapping("/register")
    @Operation(summary = "用户添加/更新（仅超管可访问）", description = "需要超管权限和user:edit权限")
    @PreAuthorize("hasRole('ROLE_SUPER_ADMIN') and hasPermission('', 'user:edit')")
    public CommonResult register(@RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user); // 复制DTO字段到实体
        user.setStatus(1); // 设置默认状态
        boolean result = userService.saveOrUpdateUser(user);
        if (result) {
            return CommonResult.success(user.getId(), "操作成功"); // 返回用户ID
        } else {
            return CommonResult.failed("操作失败");
        }
    }


    /**
     * 查询用户列表（普通用户和超管都可访问）
     */
    @GetMapping("/page")
    @Operation(summary = "查询用户分页", description = "需要user:list权限")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'USER') and hasPermission('', 'user:page')")
    public CommonResult page(
            @RequestParam(required = true) Integer pageNumber,
            @RequestParam(required = true) Integer pageSize) {
        Page<User> page = new Page<>(pageNumber, pageSize);
        Page<User> pageResp = userService.page(page);
        return CommonResult.success(pageResp);
    }


}
